import React,{useEffect, useState} from 'react'
import logoImg from '../assets/logo.jpg'
import { CaretDownOutlined  } from '@ant-design/icons';
import { Dropdown, Menu,message } from 'antd';
import defaultAvatar from '../assets/defaultAvatar.png'
import { useNavigate } from 'react-router-dom';


export default function Header() {
  //点击退出登录
  const navigate = useNavigate()
  //头像
  const [avatar,setAvatar] = useState(defaultAvatar)
  //名称
  const [username,setUsername] = useState("游客")

  //生命周期..模拟componentDidMout
  useEffect(()=>{
    let username1 = localStorage.getItem('username')
    let avatar1 = localStorage.getItem('avatar')
    // username1 从数据中查看有无名称，有就显示，无就显示默认‘游客’
    if(username1){
      setUsername(username1)
    }
    //头像
    if(avatar1){
      // http://47.93.114.103:6688/
      setAvatar('http://47.93.114.103:6688/' + avatar1)
    }
  },[localStorage.getItem('avatar')])

  //实现点击退出登录
  const logout = ()=>{
    localStorage.clear();   //清除localStorage中的数据
    message.success('退出成功，即将返回登录页')
    setTimeout(()=>navigate('/login'),1500)
  }

  //点击修改资料跳转
  const gomeans = ()=>{
    navigate('/means')
  }

  const menu = (
    <Menu>
        <Menu.Item key={1} onClick={gomeans}>修改资料</Menu.Item>
        <Menu.Divider/>
        {/* 下面方法退出登录用户数据还在.. 不严谨，应通过事件useNavigate (Hooks)*/}
        {/* <Menu.Item key={2}><Link to='/login'>退出登录</Link></Menu.Item> */}
        <Menu.Item key={2} onClick={logout}>退出登录</Menu.Item>
    </Menu>
);

    return (
        <header>
            <img src={logoImg} className='logo'></img>
            <div className='right'>
                <Dropdown overlay={menu}>
                    <a className='ant-dropdown-link' onClick={(e) => e.preventDefault()}>
                      <img src={avatar} className='avatar'/>
                      <span>{username}</span>
                      <CaretDownOutlined />
                    </a>
                </Dropdown>
            </div>
        </header>
    )
}
